include(CheckCXXSourceRuns)
include(CheckIncludeFileCXX)
include(FindPackageHandleStandardArgs)

if(SPIDERMONKEY_ROOT)
    find_path(
        SPIDERMONKEY_INCLUDE_DIR
        jsapi.h
        PATHS "${SPIDERMONKEY_ROOT}/include"
        NO_DEFAULT_PATH)

    find_library(
        SPIDERMONKEY_LIBRARY
        NAMES mozjs
        PATHS "${SPIDERMONKEY_ROOT}/lib"
        NO_DEFAULT_PATH)		
else()
	set(Spidermonkey_FIND_QUIETLY TRUE)
	
    find_path(SPIDERMONKEY_INCLUDE_DIR jsapi.h)

	find_library(SPIDERMONKEY_LIBRARY NAMES mozjs)
endif()

set(SPIDERMONKEY_LIBRARIES ${SPIDERMONKEY_LIBRARY})

get_filename_component(SPIDERMONKEY_LIB_DIR ${SPIDERMONKEY_LIBRARIES} PATH)
get_filename_component(SPIDERMONKEY_LIB ${SPIDERMONKEY_LIBRARIES} NAME)
link_directories(${SPIDERMONKEY_LIB_DIR})

message(STATUS "${SPIDERMONKEY_LIB_DIR}")

# We only support versions of SpiderMonkey which enforce JS_THREADSAFE
set(SPIDERMONKEY_DEFINITIONS ${SPIDERMONKEY_DEFINITIONS} -DJS_THREADSAFE)

set(CMAKE_REQUIRED_INCLUDES ${SPIDERMONKEY_INCLUDE_DIR})
set(CMAKE_REQUIRED_DEFINITIONS ${SPIDERMONKEY_DEFINITIONS})
list(APPEND CMAKE_REQUIRED_LIBRARIES ${SPIDERMONKEY_LIBRARY})

check_cxx_source_runs(
    "#include <jsapi.h>
     int main() {
		#if JS_VERSION >= 180
			return 0;
		# else
			return 1;
		#endif
     }"
    SPIDERMONKEY_RUNS)

find_package_handle_standard_args(
    Spidermonkey
    DEFAULT_MSG
    SPIDERMONKEY_LIBRARY
    SPIDERMONKEY_INCLUDE_DIR
    SPIDERMONKEY_RUNS)

if(SPIDERMONKEY_FOUND)
    check_include_file_cxx("${SPIDERMONKEY_INCLUDE_DIR}/js-config.h" SPIDERMONKEY_JS_CONFIG_HEADER)

    set(CMAKE_REQUIRED_INCLUDES ${SPIDERMONKEY_INCLUDE_DIR})
    set(CMAKE_REQUIRED_DEFINITIONS ${SPIDERMONKEY_DEFINITIONS})
    set(CMAKE_REQUIRED_LIBRARIES ${SPIDERMONKEY_LIBRARY})
 
    # Check if we have GC_Zeal
    check_cxx_source_compiles(
        "#include <jsapi.h>
         int main() {
           JS_SetGCZeal((JSContext*)(0), 0, 0, 0);
         }"
        SPIDERMONKEY_HAS_GCZEAL
    )
    if(SPIDERMONKEY_HAS_GCZEAL)
      add_definitions(-DSPIDERMONKEY_HAS_GCZEAL)
    endif()
endif()

list(REMOVE_ITEM CMAKE_REQUIRED_LIBRARIES ${SPIDERMONKEY_LIBRARY})
list(REMOVE_DUPLICATES CMAKE_REQUIRED_LIBRARIES)
mark_as_advanced(SPIDERMONKEY_INCLUDE_DIR SPIDERMONKEY_LIBDIR SPIDERMONKEY_LIB)

